<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import LeftSide from './component/LeftSide.vue'
import type { Session } from './component/LeftSide.vue'
import Chat from '@/components/business/Chat/index.vue'
import { MsgType, RenderType, Sender } from '@/components/business/Chat/enum'
import { modeType, longgangModeKey, knowledgeApiConst } from '@/utils/const'
import { cloneDeep } from 'lodash-es'
import { getChatUrl } from '@/api/longgang/index'
// import logo  from '@/imgs/longgang-0x00x00x02.png'

const urlOption = getChatUrl()
const defaultType = modeType.find((o) => o.key === longgangModeKey.general)
const defaultMsg = {
	msgType: MsgType.Text,
	sender: Sender.System,
	content: defaultType?.msg,
	thinkStatus: false,
	answerStatus: false,
}
const maxWidth = ref(false)
const msgLoadStatus = ref(false)
const chatRef = ref<any>(null)
const msgText = ref('')
const reAnswer = ref('')
const currentSession = ref<Session | null>()
const leftSideRef = ref<any>(null)
const isDefault = ref(false)
const chatTypeData = computed(() => {
	if (!currentSession.value) return null
	const config = {
		apiOption: {
			headers: {},
			url: urlOption[currentSession.value.type],
			isStream: true,
			renderType: RenderType.Stream,
		},
		data: {
			currentContent: msgText.value || reAnswer.value,
			stream: true,
			model: 'deepseek-r1:32b-qwen-distill-fp16',
		},
	}
	if (currentSession.value?.type === longgangModeKey.knowledge) {
		config.apiOption.isStream = config.data.stream = false
		config.apiOption.renderType = RenderType.ApiDefCallV1
		config.apiOption.url += knowledgeApiConst.id
		config.apiOption.headers = {
			Authorization: knowledgeApiConst.Authorization,
		}
		config.data.model = ''
	}
	return config
})

// 切换宽度
function switchChatWidth() {
	maxWidth.value = !maxWidth.value
}

// 选择chat的模式
function switchMode(item: any) {
	console.log(item, 'item')
	if (!currentSession.value) {
		return
	}
	isDefault.value = false
	currentSession.value.type = item.key
	currentSession.value.title = item.title

	// 修改欢迎词
	const msgOpt = cloneDeep(defaultMsg)
	msgOpt.content = item.msg
	currentSession.value.msgList = cloneDeep([msgOpt])
	leftSideRef.value?.onUpdateItem(currentSession.value)
}

// 获取当前对话
async function getCurrentSession(session: Session) {
	chatRef.value?.onClose()
	// 新建会话的时候，需要初始化一条msgList数据
	if (session.type === longgangModeKey.default && session.msgList.length === 0) {
		session.msgList = cloneDeep([defaultMsg])
		leftSideRef.value?.onUpdateItem(session)
	}
	await nextTick()
	chatRef.value?.onReset()
	console.log(session, 'session')
	isDefault.value = session.type === longgangModeKey.default
	currentSession.value = session
	let t = setTimeout(() => {
		chatRef.value?.onScrollToBottom()
		clearTimeout(t)
	}, 200)
}

// 发送问题
async function handleSendMsg(e: any) {
	if (e?.shiftKey) {
		return
	}
	e.preventDefault && e.preventDefault()
	const { currentContent } = chatTypeData.value?.data || {}
	if (!currentContent || !currentSession.value) {
		return
	}

	// 组装消息
	// const msgOpt = cloneDeep(defaultMsg)
	// msgOpt.content = currentContent
	// msgOpt.sender = Sender.User
	// currentSession.value?.msgList.push(msgOpt)

	// 发送消息
	// 根据类型组装api需要的数据
	let submitData: any = chatTypeData.value?.data
	if (currentSession?.value.type === longgangModeKey.general) {
		// 通用模型 需要传递上下文
		const allMsgList = chatRef.value?.getMsgList() || []
		allMsgList.filter((m: any) => m.sender !== Sender.System)
		console.log(chatTypeData.value?.data, 'chatTypeData.value?.data', allMsgList)
		let contextList = []
		allMsgList.forEach((a: any) => {
			if (a.sender !== Sender.System) {
				if (a.sender === Sender.Ai) {
					let matchTextList: any[] = []
					a.content.replace(/<div\s+class="think"[^>]*>([\s\S]*?)<\/div>/g, (match: any, p1: any) => {
						matchTextList.push(p1)
					})
					if (matchTextList.length) {
						contextList.push({
							role: 'assistant',
							content: matchTextList[0],
						})
					}
				} else {
					contextList.push({
						role: 'user',
						content: a.content,
					})
				}
			}
		})
		contextList.push({
			role: 'user',
			content: currentContent,
		})
		submitData.messages = contextList
	} else {
		// 知识库
		submitData.context = []
		submitData.question = submitData.currentContent
	}
	console.log(submitData, '====提交的数据')
	chatRef.value.onSendMsg(submitData)
	msgText.value = ''
	reAnswer.value = ''

	await nextTick()
	// 更新indexdb数据
	updatedMsgList('pop')
}

// 重新回答
function handleReAnswer(obj: any) {
	console.log(obj, 'obj')
	reAnswer.value = obj.content
	handleSendMsg({})
}

// 更新会话列表
function updatedMsgList(fnName = '') {
	if (!currentSession.value) return
	const currentList = chatRef.value?.getMsgList() || []
	if (fnName) {
		// 删除最后一条数据，最后一条数据还没有真正的内容
		currentList[fnName]()
	}
	const currSession = cloneDeep(currentSession.value)
	currSession.msgList = currentList
	leftSideRef.value?.onUpdateItem(currSession)
}

// 消息结束
function onMsgEnd() {
	updatedMsgList('')
}

watch(
	() => msgLoadStatus.value,
	 (status) => {
		if(status) {
			document.body.click()
		}
	},
	{
		immediate: true,
	}
)
</script>
<template>
	<div :class="['longgang-chat-route', maxWidth ? 'max-chat' : '']">
		<div class="left-container">
			<LeftSide ref="leftSideRef" @current-session="getCurrentSession" />
		</div>
		<div class="chat-container">
			<div class="head">
				<div class="switch-chat">
					<i class="icon" @click="switchChatWidth"></i>
				</div>
			</div>
			<div class="chat">
				<div class="body">
					<!--
						:avatar="{
							reply: logo
						}"
					 -->
					<Chat
						ref="chatRef"
						v-if="chatTypeData"
						method="post"

						v-bind="chatTypeData.apiOption"
						v-model:msgLoadStatus="msgLoadStatus"
						:defaultList="currentSession?.msgList"
						@on-msg-end="onMsgEnd"
						@on-re-answer="handleReAnswer"
					></Chat>
					<div class="chat-sel" v-if="isDefault">
						<div class="title">
							<svg
								viewBox="0 0 24 24"
								fill="none"
								xmlns="http://www.w3.org/2000/svg"
								width="1em"
								height="1em"
								focusable="false"
								aria-hidden="true"
							>
								<path
									fill-rule="evenodd"
									clip-rule="evenodd"
									d="M4 2a2 2 0 0 0-2 2v5c0 1.1.9 2 2 2h5a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H4Zm0 11a2 2 0 0 0-2 2v5c0 1.1.9 2 2 2h5a2 2 0 0 0 2-2v-5a2 2 0 0 0-2-2H4Zm9 2c0-1.1.9-2 2-2h5a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-5Zm2-13a2 2 0 0 0-2 2v5c0 1.1.9 2 2 2h5a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-5Zm0 2h5v5h-5V4Z"
									fill="currentColor"
								></path>
							</svg>
							<p>智能应用</p>
						</div>
						<div class="tab">
							<div class="item" v-for="t in modeType" @click="switchMode(t)">
								<!-- <img src="@/imgs/longgang-0x00x00x01.png" alt="" /> -->
								<span>{{ t.title }}</span>
								<!-- <svg
									width="16px"
									height="16px"
									viewBox="0 0 16 16"
									version="1.1"
									xmlns="http://www.w3.org/2000/svg"
									xmlns:xlink="http://www.w3.org/1999/xlink"
								>
									<title>置顶备份 3</title>
									<g id="页面-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
										<g id="新建会话-查看更多" transform="translate(-1363, -782)" fill="#9FA5B5" fill-rule="nonzero">
											<g id="置顶备份-3" transform="translate(1363, 782)">
												<path
													d="M15.7943353,5.44963875 L10.5511034,0.206406863 C10.4185726,0.0737663175 10.2386041,-0.000524657641 10.0511004,2.789477e-06 C9.86359663,-0.000524652643 9.68362818,0.0737663221 9.55109735,0.206406863 L6.1230765,3.63682772 C5.86304368,3.60752767 5.60154956,3.5931041 5.33987174,3.59362746 C3.74288439,3.59120598 2.19290039,4.13392616 0.946245034,5.13203681 C0.78962135,5.25779575 0.693863622,5.44422381 0.682873869,5.6447868 C0.671884116,5.8453498 0.746699237,6.04112431 0.888644684,6.1832432 L4.75506819,10.0496667 L0.171040322,14.6288945 C0.115075506,14.6846052 0.0805204124,14.7582472 0.0734397351,14.8368958 L0.00143929743,15.6289006 C-0.00734500068,15.723995 0.0243639281,15.8183869 0.088777809,15.8888919 C0.15319169,15.9593969 0.244342271,15.9994825 0.339841354,15.9993035 C0.350241424,15.9993035 0.360641475,15.9993035 0.371841536,15.9969029 L1.16384635,15.9249024 C1.24260042,15.9176052 1.31625605,15.8827604 1.37184763,15.8265018 L5.95507548,11.243274 L9.82149898,15.1096975 C9.95402983,15.242338 10.1339983,15.316629 10.321502,15.3160987 C10.5358456,15.3165976 10.7387409,15.2194199 10.8727054,15.0520971 C12.0391531,13.5928182 12.5765992,11.7291726 12.3663145,9.87286564 L15.7943353,6.44484479 C16.0685549,6.16977841 16.0685549,5.72470513 15.7943353,5.44963875 Z M11.2807079,8.79365906 L10.7599047,9.31526224 L10.8399052,10.0472667 C10.9669051,11.1795252 10.741152,12.3233785 10.1935012,13.3224866 L2.68065557,5.80484091 C3.67882816,5.25538212 4.82292294,5.0292466 5.95507548,5.15763696 L6.68707993,5.23843746 L7.20868311,4.7176343 L10.0535004,1.872817 L14.1279252,5.94724176 L11.2807079,8.79445907 L11.2807079,8.79365906 Z"
													id="形状"
												></path>
											</g>
										</g>
									</g>
								</svg> -->
							</div>
						</div>
					</div>
				</div>
				<div class="ctrl">
					<p class="mode-type">deepseek</p>
				</div>
				<div class="input" :class="[isDefault || msgLoadStatus ? 'disabled' : '']">
					<div class="textarea">
						<el-input
							type="textarea"
							placeholder="请输入消息"
							v-model="msgText"
							:autosize="{ minRows: 1, maxRows: 2 }"
							resize="none"
							@keydown.enter="handleSendMsg"
						></el-input>
						<i class="icon" @click="handleSendMsg"></i>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<style lang="scss" scoped>
.longgang-chat-route {
	height: 100%;
	display: flex;
	overflow: hidden;
	&.max-chat {
		.left-container {
			width: 0;
			overflow: hidden;
		}
		.chat-container {
			.head {
				.switch-chat {
					transform: rotate(180deg);
				}
			}
		}
	}
	.left-container {
		width: 320px;
		height: 100%;
		background-color: #fff;
		transition: width 0.15s;
	}
	.chat-container {
		flex: 1;
		transition: width 0.15s;
		display: flex;
		flex-direction: column;
		$head-height: 68px;

		.head {
			height: $head-height;
			display: flex;
			align-items: center;
			padding: 0 14px;
			border-bottom: 1px solid #e2e6ef;
			.switch-chat {
				display: flex;
				transition: all 0.15s;
				.icon {
					width: 36px;
					height: 34px;
					background: url(@/imgs/fold.svg) no-repeat center center;
					cursor: pointer;
				}
			}
		}
		.chat {
			width: 100%;
			height: calc(100vh - $head-height);
			display: flex;
			flex-direction: column;
			// padding: 0 100px;
			margin: 0 auto;
			max-width: 1020px;
			.body {
				flex: 1;
				height: 0;
				background-color: #f6f7fb;
				position: relative;
				.chat-sel {
					position: absolute;
					left: 10px;
					top: 80px;
					padding: 12px 46px;
					width: 100%;
					.title {
						display: flex;
						align-items: flex-end;
						svg {
							vertical-align: bottom;
							path {
								color: #999;
							}
						}
						p {
							margin-left: 6px;
							color: #999;
							font-size: 14px;
						}
					}
					.tab {
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin-top: 12px;
						.item {
							width: 45%;
							height: 88px;
							background: #fff;
							border-radius: 8px;
							display: flex;
							align-items: center;
							padding: 20px;
							font-size: 18px;
							cursor: pointer;
							span {
								font-weight: 600;
								flex: 1;
								margin-left: 10px;
							}
							img {
								height: 48px;
							}
						}
					}
				}
			}
			.ctrl {
				width: 100%;
				padding: 20px 0;
				.mode-type {
					display: inline-block;
					padding: 4px 10px;
					background: #fff;
				}
			}
			.input {
				height: 100px;
				padding-bottom: 20px;
				position: relative;
				&.disabled {
					&::before {
						display: block;
						content: '';
						position: absolute;
						left: 0;
						top: 0;
						width: 100%;
						height: 100%;
						cursor: not-allowed;
						z-index: 2;
					}
				}
				.textarea {
					height: 100%;
					background: #fff;
					display: flex;
					align-items: center;
					border-radius: 100px;
					padding: 0 16px;
					:deep(.el-textarea) {
						.el-textarea__inner {
							border: 0;
							box-shadow: none;
						}
					}
					.icon {
						width: 36px;
						height: 34px;
						padding: 10px;
						background: url(@/imgs/send-0x001.svg) no-repeat center center;
						cursor: pointer;
					}
				}
			}
		}
	}
}
</style>
